package com.ai.common.http;

import com.ai.common.enums.ConfigModuleEnum;
import com.ai.common.http.dto.GetWXTokenResponse;
import com.ai.common.http.dto.WXOpenIdResponse;
import com.ai.common.http.dto.WxMsgSecCheckResponse;
import com.ai.sevice.ai.remote.CompletionsResponse;
import com.ai.sevice.config.ConfigService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：shengwenyang
 * @date ：Created in 2023/5/10 10:51
 * @description：
 * @version:
 */
@Component
public class WeiXinApiClient {

    private static final String WX_URL = "https://api.weixin.qq.com";

    private static final String WX_APP_ID = "wx320f55e68de8c25a";

    private static final String WX_SECRET = "d272095ec52ad149e5c29d72d6999b39";

    @Autowired
    private ConfigService configService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 小程序登录 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     * @param wxCode
     * @return
     */
    public WXOpenIdResponse getWxOpenId(String wxCode){
        if (StringUtils.isBlank(wxCode)){
            return null;
        }
        String url = WX_URL + "/sns/jscode2session?appid=" + WX_APP_ID + "&secret=" + WX_SECRET + "&js_code=" + wxCode + "&grant_type=authorization_code";
        //log.info("getWXOpenIdRequest -> " + url);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        //log.info("getWXOpenIdResponse -> " + forEntity.getBody());
        return JSON.parseObject(forEntity.getBody(),WXOpenIdResponse.class);
    }

    /**
     * 获取微信token
     * 文档  https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
     * @return
     */
    public GetWXTokenResponse getWxToken(){
        String url = WX_URL + "/cgi-bin/token?grant_type=client_credential&appid="+ WX_APP_ID +"&secret=" + WX_SECRET;
        //log.info("getWXOpenIdRequest -> " + url);
        ResponseEntity<GetWXTokenResponse> forEntity = restTemplate.getForEntity(url, GetWXTokenResponse.class);
        //log.info("getWXOpenIdResponse -> " + forEntity.getBody());
        if (forEntity.getBody() != null && StringUtils.isNotBlank(forEntity.getBody().getAccess_token())){
            configService.addOrUpdate(ConfigModuleEnum.DEFAULT.getModule(), "weixinToken",forEntity.getBody().getAccess_token());
        }
        return forEntity.getBody();
    }

    /**
     * 微信文本内容安全识别
     * 文档 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/sec-center/sec-check/msgSecCheck.html
     * @param openid 用户openid
     * @param content 检测内容
     */
    public WxMsgSecCheckResponse wxMsgSecCheck(String openid, String content){
        if (StringUtils.isBlank(openid) || StringUtils.isBlank(content)){
            return null;
        }
        WxMsgSecCheckResponse body = getWxMsgSecCheckResponse(openid, content);
        if (body == null){
            return null;
        }
        Integer errcode = body.getErrcode();
        if (errcode != null && (errcode.equals(40001) || errcode.equals(420001) || errcode.equals(42001))){
            //重新获取token
            getWxToken();
            body = getWxMsgSecCheckResponse(openid, content);
        }
        return body;
    }

    private WxMsgSecCheckResponse getWxMsgSecCheckResponse(String openid, String content) {
        String weixinToken = configService.getValue(ConfigModuleEnum.DEFAULT.getModule(), "weixinToken");
        String url = WX_URL + "/wxa/msg_sec_check?access_token=" + weixinToken;
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("openid",openid);
        requestMap.put("content",content);
        requestMap.put("scene",2);
        requestMap.put("version",2);
        //设置请求头参数
        HttpHeaders head = new HttpHeaders();
        //封装请求参数
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(requestMap),head);
        ResponseEntity<WxMsgSecCheckResponse> responseEntity = null;
        ResponseEntity<WxMsgSecCheckResponse> wxMsgSecCheckResponseResponseEntity = responseEntity = restTemplate.postForEntity(url, entity, WxMsgSecCheckResponse.class, new HashMap<>());
        return wxMsgSecCheckResponseResponseEntity.getBody();
    }

}
